<template>
  <div class="container">
    <div class="title">
      <h1 class="table-name" :title="title">
        {{ title }}
      </h1>
      <div v-show="!isInSql" class="btn-box">
        <a-button
          v-if="importType === 'table'"
          type="primary"
          ghost
          @click="editDataSetSetting"
          >编辑
        </a-button>
        <a-button
          type="primary"
          ghost
          :loading="isDownloading"
          @click="downloadDataSet"
          >{{ isDownloading ? '下载中' : '下 载' }}</a-button
        >
        <a-button type="primary" ghost @click="setDeleteVisible"
          >删 除</a-button
        >
      </div>
    </div>
    <div
      v-if="!selectedGraphFileName && selectedKGraphFileId < 0"
      class="infos"
    >
      <span>大小：{{ size }}</span>
      <span>行数：{{ count }}</span>
      <span>拥有者：{{ owner }}</span>
      <span>创建时间：{{ createTime }}</span>
      <span>数据源类型：{{ importType }}</span>
      <span v-if="importType === 'http'">url：{{ url }}</span>
      <span v-if="importType === 'http'">
        状态
        <a-tooltip placement="top">
          <template slot="title">
            该设置更改后，有5-10分钟延迟生效时间
          </template>
          <a-icon-font type="iconbangzhu" />
        </a-tooltip>
        :
        <span v-if="isInSql">{{ status ? 'on' : 'off' }}</span>
        <a-switch v-else v-model="status" @change="onStatusChange" />
      </span>
    </div>
    <div class="data-table">
      <dataset-preview-table
        v-if="datasetInfo"
        :head="datasetInfo ? datasetInfo.head : []"
        :data="datasetInfo ? datasetInfo.data : []"
        :height="previewTableHeight"
        data-type="table"
      />
      <pre v-else-if="graphFileContent" class="graph-content">
        {{ graphFileContent }} 
      </pre>
      <pre v-else-if="KGraphFileContent" class="graph-content">
        {{ KGraphFileContent }} 
      </pre>
    </div>
  </div>
</template>

<script lang="ts">
/**
 * content of data management view
 * show data of selected dataset
 * @author Huihua Lu
 */
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import DataStore from '@/store/modules/data'
import DatasetPreviewTable from '@/components/data/DatasetPreviewTable.vue'
import DeleteDatasetContent from '@/components/data/DeleteDatasetContent.vue'
import { Modal } from 'ant-design-vue'
import {
  queryGraphFileByName,
  queryDatasetUsedInfo,
  downloadDataSetFile,
  downloadKGFile,
  queryKGFileById,
} from '@/api/data'

@Component({
  components: {
    DatasetPreviewTable,
    DeleteDatasetContent,
  },
})
export default class DataViewContent extends Vue {
  @Prop() public isInSql: any
  private datasetInfo: any = null
  private status: any = false
  private transferUserId: any = -1

  private isDownloading: boolean = false
  private deleteVisible: boolean = false
  private graphFileContent: string = '' // 图文件预览内容
  private KGraphFileContent: string = '' //  图谱文件预览

  public get datasetId() {
    return DataStore.selectedDatasetId
  }

  public get selectedGraphFileName() {
    return DataStore.selectedGraphFileName
  }

  public get selectedKGraphFileId() {
    return DataStore.selectedKGraphFileId
  }

  public get title() {
    if (this.datasetInfo) {
      return this.datasetInfo.name
    }
    if (this.selectedGraphFileName) {
      return this.selectedGraphFileName
    }
    if (this.selectedKGraphFileId > -1) {
      return DataStore.selectedKGraphTitle
    }
    return ''
  }
  //  获取重命名后的新名称
  public get datasetNewName() {
    return DataStore.newDatasetName
  }
  //  更新 重命名后的数据集名
  @Watch('datasetNewName')
  handleDatasetName(newValue: string) {
    if (newValue.length > 0) {
      this.datasetInfo = {
        ...this.datasetInfo,
        name: newValue,
      }
    }
  }

  public get previewTableHeight() {
    const { height } = this.$el.getBoundingClientRect()
    return height - 90 - 48 // 48是上下padding，90是表格上方摘要区
  }

  public async created(): Promise<void> {
    if (
      !this.selectedGraphFileName &&
      this.selectedKGraphFileId < 0 &&
      this.datasetId > 0
    ) {
      await DataStore.queryDataset(this.datasetId)
      this.datasetInfo = DataStore.selectedDatasetInfo
      this.status = this.datasetInfo.incrementalDataConfig === 'on'
    } else if (this.selectedGraphFileName) {
      this.queryGraphFileByName(this.selectedGraphFileName)
    } else if (this.selectedKGraphFileId > 0) {
      this.queryKGraphFileById(this.selectedKGraphFileId)
    }
  }

  public selectedDatabaseType: string = 'mysql'

  // 根据用户选择的数据集来请求数据
  @Watch('datasetId')
  public async handleChange() {
    this.graphFileContent = ''
    this.KGraphFileContent = ''
    if (this.datasetId > -1) {
      await DataStore.queryDataset(this.datasetId)
      this.datasetInfo = DataStore.selectedDatasetInfo
      this.status = this.datasetInfo.incrementalDataConfig === 'on'
    }
  }

  /**
   * 图文件
   */
  @Watch('selectedGraphFileName')
  public handleGraphFileNameChange() {
    this.datasetInfo = null
    this.KGraphFileContent = ''
    if (this.selectedGraphFileName) {
      this.queryGraphFileByName(this.selectedGraphFileName)
    }
  }
  /**
   * 知识图谱文件
   */
  @Watch('selectedKGraphFileId')
  public handleSelectedKGraphFileId() {
    this.graphFileContent = ''
    this.datasetInfo = null
    if (this.selectedKGraphFileId > -1) {
      this.queryKGraphFileById(this.selectedKGraphFileId)
    }
  }

  /**
   * 预览图数据文件内容
   */
  public async queryGraphFileByName(name: string) {
    const response: any = await queryGraphFileByName({
      data: {
        fileName: name,
      },
    })
    if (response.data.code === 100) {
      const { result } = response.data
      if (result.format === 'json' || result.format === 'gml') {
        this.graphFileContent = response.data.result.content
        this.datasetInfo = null
      } else {
        // 返回csv表格数据
        this.graphFileContent = ''
        this.datasetInfo = {
          name,
          ...result.content,
        }
      }
    }
  }

  public async queryKGraphFileById(id: number) {
    const response: any = await queryKGFileById({
      params: {
        knowledgeGraphFileId: id,
      },
    })
    if (response.data.code === 200) {
      this.KGraphFileContent = response.data.data.content
      DataStore.setSelectedKGraphTitle(response.data.data.name)
      this.datasetInfo = null
    }
  }

  public async onStatusChange(value: any) {
    const passData = {
      id: this.datasetId,
      incrementalDataConfig: value ? 'on' : 'off',
      preIncrementalDataConfig: !value ? 'on' : 'off',
    }
    await DataStore.updateHttpDataStatus(passData)
  }

  public get size() {
    return this.datasetInfo ? this.datasetInfo.size : ''
  }

  public get count() {
    return this.datasetInfo ? this.datasetInfo.count : ''
  }

  public get owner() {
    return this.datasetInfo ? this.datasetInfo.owner : ''
  }

  public get createTime() {
    if (!this.datasetInfo) {
      return ''
    }
    const year = this.datasetInfo.createTime.slice(0, 4)
    const month = Number.parseInt(
      this.datasetInfo.createTime.slice(5, 7),
      10
    ).toString()
    const day = Number.parseInt(
      this.datasetInfo.createTime.slice(8, 10),
      10
    ).toString()
    return `${year}/${month}/${day}`
  }

  // 导入数据类型
  public get importType() {
    return this.datasetInfo ? this.datasetInfo.type : ''
  }

  // 导入数据url
  public get url() {
    const { protocol, host } = window.location
    const datasetConfig = this.datasetInfo ? this.datasetInfo.dataConfig : ''
    return `${protocol}//${host}/api${datasetConfig}`
  }
  /**
   * 下载KG file
   */
  public async downloadKGFile() {
    const response = await downloadKGFile({
      params: {
        knowledgeGraphFileId: this.selectedKGraphFileId,
      },
    })
    if (response.status === 200) {
      const downloadName = this.title
      const blob = new Blob([response.data], {
        type: 'application/json',
      })
      const element = document.createElement('a')
      element.setAttribute('href', URL.createObjectURL(blob))
      element.setAttribute('download', decodeURIComponent(downloadName))
      element.style.display = 'none'
      element.click()
      this.$message.success('下载成功！', 3)
    } else {
      this.$message.error('下载失败！', 3)
    }
    this.isDownloading = false
  }

  /* 下载数据集到本地 */
  public async downloadDataSet() {
    if (this.isDownloading) {
      return
    }
    this.isDownloading = true
    if (this.selectedKGraphFileId > -1) {
      this.downloadKGFile()
      return
    }
    const paraId = this.selectedGraphFileName
      ? this.selectedGraphFileName
      : this.datasetId
    const paraType = this.selectedGraphFileName ? 'graph' : 'dataset'
    const response = await downloadDataSetFile({
      data: {
        datasetId: paraId,
        type: paraType,
      },
    })
    if (response.status === 200) {
      const downloadName =
        response.headers['content-disposition'].split('filename=')[1]
      const blob = downloadName.includes('.json')
        ? new Blob([JSON.stringify(response.data)], {
            type: 'application/json',
          })
        : new Blob([response.data], {
            type: 'application/octet-stream',
          })
      const element = document.createElement('a')
      element.setAttribute('href', URL.createObjectURL(blob))
      element.setAttribute('download', decodeURIComponent(downloadName))
      element.style.display = 'none'
      element.click()
      this.$message.success('下载成功！', 3)
    } else {
      this.$message.error('下载失败！', 3)
    }
    this.isDownloading = false
  }

  /* 删除数据集 */
  public async setDeleteVisible() {
    let dataset: any
    if (!this.selectedGraphFileName && this.selectedKGraphFileId < 0) {
      const response = await queryDatasetUsedInfo({
        data: { datasetId: this.datasetId },
      })
      dataset = response.data.result
      if (dataset.length !== 0) {
        this.transferUserId = dataset[0].userId
      }
    }
    this.deleteVisible = true
    Modal.confirm({
      title: '确认要删除该数据表吗？',
      content: () =>
        this.$createElement('delete-dataset-content', {
          props: {
            dataset,
            setTransferUserId: (value: any) => {
              this.transferUserId = value
            },
          },
        }),
      okText: '确定',
      cancelText: '取消',
      onOk: () => this.deleteDataset(),
      onCancel: this.cancelDelete,
    })
  }

  /** 取消 */
  public cancelDelete() {
    this.deleteVisible = false
  }

  /** 删除数据表 */
  public async deleteDataset() {
    if (this.datasetId > -1 && !this.selectedGraphFileName) {
      const response = await DataStore.deleteDataset({
        id: this.datasetId,
        transferUserId: this.transferUserId,
      })
      if (response.data.code === 100) {
        DataStore.setSelectedDatasetId(-1)
        DataStore.setDatasetId('')
        DataStore.setSelectedKGraphFileId(-1)
        this.$router.push('/management/data')
      }
    } else if (this.selectedGraphFileName) {
      const paraId =
        this.datasetId && this.datasetId > -1 ? this.datasetId : null
      const response = await DataStore.deleteGraphFile({
        fileName: this.selectedGraphFileName,
        datasetId: paraId,
      })
      if (response.data.code === 100) {
        DataStore.setSelectedGraphFileName('')
        DataStore.setDatasetId('')
        DataStore.setSelectedKGraphFileId(-1)
        this.$router.push('/management/data')
      }
    } else if (this.selectedKGraphFileId > -1) {
      const formData = new FormData()
      formData.append('knowledgeGraphFileId', String(this.selectedKGraphFileId))
      const response = await DataStore.deleteKGraphFile(formData)
      if (response.data.code === 200) {
        DataStore.setSelectedGraphFileName('')
        DataStore.setSelectedKGraphFileId(-1)
        DataStore.setDatasetId('')
        this.$router.push('/management/data')
      } else {
        this.$message.error(response.data.message)
      }
    }
    this.deleteVisible = false
  }

  /** 编辑数据 */
  public async editDataSetSetting() {
    DataStore.setDatasetEditModalVisible(true)
    DataStore.setIsClearForm(true)
  }
}
</script>

<style lang="less" scoped>
@import '@/constants';

.container {
  height: 100%;
  margin: 0 24px;
  padding: 24px 0;

  .graph-content {
    border: 1px solid #e9e9e9;
    height: calc(100vh - 340px);
  }
}

.title {
  align-items: center;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;

  .table-name {
    display: inline-block;
    font-size: @TEXT_FONT_SIZE_BIG;
    font-weight: bold;
    max-width: 50%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.infos {
  align-items: center;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  margin-top: 12px;

  span {
    margin-right: 20px;
  }
}

.data-table {
  margin-top: 30px;
}

.btn-box {
  align-self: flex-end;

  .ant-btn + .ant-btn {
    margin-left: 20px;
  }
}
</style>
